
import OvenLiveKit from 'ovenlivekit'
import { Device, Devices, StreamConfig, screenFace, CameraFace } from "@/tyeps/OvenLiveKit"
import { v4 as uuidv4 } from 'uuid';

export default class LiveStream {
  Client: any;
  Ws: string;
  id: string
  config = {
    error: (error: any) => {
      console.error(error);
    },
    connected: (event: any) => {
    },
    connectionClosed: (type: any, event: any) => {
    },
    iceStateChange: (state: any) => {
    }
  }

  constructor(id: string, Ws: string) {
    this.Ws = Ws
    this.id = id
    this.Client = OvenLiveKit.create(this.config);
    this.Client.attachMedia(document.getElementById(this.id))
  }
  setMediaStream(s: MediaStream) {

    return this.Client.setMediaStream(s)
  }
  async startLive() {
    this.Client.startStreaming(this.Ws);
  }
  remove() {
    this.Client?.remove()
  }
  static StreamStop(s:MediaStream){
     // 获取音频轨道
     const audioTracks = s?.getAudioTracks();

     // 获取视频轨道
     const videoTracks = s?.getVideoTracks();
     audioTracks?.forEach(e => {
      e.stop()
    })
    videoTracks?.forEach(e => {
      e.stop()
    })
  }
  static chnageStream(data: CameraFace | screenFace) {
    // 获取音频轨道
    const audioTracks = data.stream?.getAudioTracks();

    // 获取视频轨道
    const videoTracks = data.stream?.getVideoTracks();
    audioTracks?.forEach(e => {
      e.enabled = data.isAudio
      if (data.isStop) {
        e.stop()
      }
    })
    videoTracks?.forEach(e => {
      e.enabled = data.isVideo
      if (data.isStop) {
        e.stop()
      }
    })
  }
  static async getUserMedia(Config: CameraFace): Promise<CameraFace> {
    const res = await navigator.mediaDevices.getUserMedia({ audio: Config.audio, video: Config.video })
    Config.id = uuidv4()
    Config.stream = res

    return Config
  }
  static async getDisplayMedia(Config: screenFace): Promise<screenFace> {
    const res = await navigator.mediaDevices.getDisplayMedia({ audio: Config.audio, video: Config.video })
    Config.id = uuidv4()
    Config.stream = res
    return Config
  }
  static async getLocalDevices() {
    const devices: Devices = {
      // 麦克风
      audioinput: [],
      // 扬声器
      audiooutput: [],
      // 视频
      videoinput: [],
      // 显示器
      screen: [],
    }
    window.live.getScreen().then((datas: any) => {
      for (let index = 0; index < datas.length; index++) {
        devices.screen.push({
          deviceId: datas[index].id,
          label: datas[index].name
        })

      }
    })
    OvenLiveKit.getDevices().then((datas: Devices) => {
      devices.audioinput.push(...datas.audioinput)
      devices.audiooutput.push(...datas.audiooutput)
      devices.videoinput.push(...datas.videoinput)
    }).catch((error: any) => {
      console.error(error)
      console.error("没有设备")
    }).finally(() => {
      console.log(devices)
    })
  }
}
